"""
用户登陆/注册
@author:yczha
"""
import wx
import os.path
from src.config import settings
from src.models.user import User
from src.api.login import login as api_login, register as api_register
from src.schemas.login import UserAuth, UserCreate


class LoginDialog(wx.Dialog):
    def __init__(self, parent):
        super(LoginDialog, self).__init__(parent, title='用户登录')
        panel = wx.Panel(self)
        back = wx.StaticBitmap(panel, bitmap=wx.Bitmap(
            os.path.join(settings.assets_dir, 'login_page.png')))
        self.username = wx.TextCtrl(back)
        self.password = wx.TextCtrl(back, style=wx.TE_PASSWORD)
        user = User.get_user()
        if user:
            self.username.SetValue(user.username)
            self.password.SetValue(user.password)
        self.username.SetPosition((180, 90))
        self.password.SetPosition((180, 130))
        login_button = wx.BitmapButton(back, bitmap=wx.Bitmap(
            os.path.join(settings.assets_dir, 'login.png')))
        login_button.SetPosition((80, 200))
        login_button.Bind(wx.EVT_BUTTON, self._login)
        register_button = wx.BitmapButton(back, bitmap=wx.Bitmap(
            os.path.join(settings.assets_dir, 'register.png')))
        register_button.SetPosition((250, 200))
        register_button.Bind(wx.EVT_BUTTON, self._register)

        panel.Fit()
        self.Fit()
        self.Centre()

    def _login(self, e):
        """登陆函数"""
        user_info = {'username': self.username.GetValue(
        ), 'password': self.password.GetValue()}
        try:
            user_obj = UserAuth(**user_info)
        except ValueError as e:
            err = eval(e.json())[0]['msg']
            wx.MessageBox(f'{err}', '错误提示', wx.OK | wx.ICON_ERROR)
            return
        user = User.get_user(require_login=True)
        if user and user_obj.username == user.username:
            wx.MessageBox(f'{user.username}, 你已登陆!', '提示信息',
                          wx.OK | wx.ICON_INFORMATION)
            self.EndModal(wx.ID_OK)
            self.Destroy()
            return
        self._check_login(user_obj=user_obj)

    def _register(self, e):
        """注册函数"""
        user_info = {'nickname': self.username.GetValue(
        ), 'password': self.password.GetValue()}
        if user_info['nickname'].isdigit():
            user_info['phone'] = user_info['nickname']
        else:
            user_info['email'] = user_info['nickname']
        try:
            user_obj = UserCreate(**user_info)
        except ValueError as e:
            err = eval(e.json())[0]['msg']
            wx.MessageBox(f'{err}', '错误提示', wx.OK | wx.ICON_ERROR)
            return
        user = User.get_user(require_login=True)
        if user and user_obj.nickname == user.username:
            wx.MessageBox(f'{user.username}, 用户已存在!', '提示信息',
                          wx.OK | wx.ICON_WARNING)
            self.EndModal(wx.ID_OK)
            self.Destroy()
            return
        status, msg = api_register(user_obj=user_obj)
        self._check_register(status, msg, user_obj=user_obj)

    def _check_register(self, status, msg, user_obj=None):
        if status == 1000:
            wx.MessageBox(msg, '成功提示', wx.OK | wx.ICON_INFORMATION)
            self.EndModal(wx.ID_OK)
            return
        elif status == 1004:
            code_dlg = wx.TextEntryDialog(self, msg, '输入验证码')
            while True:
                if code_dlg.ShowModal() == wx.ID_OK:
                    code = code_dlg.GetValue()
                    if not str(code).isdigit() or len(str(code)) != 6:
                        wx.MessageBox(f'验证码必须是6位数字!', '错误提示',
                                      wx.OK | wx.ICON_ERROR)
                    else:
                        break
                else:
                    return
            code_dlg.Destroy()
            if not str(code).isdigit() or len(str(code)) != 6:
                return
            new_user_obj = UserCreate(
                **user_obj.dict(exclude_none=True), code=code)
            if user_obj is not None:
                status, msg = api_register(user_obj=new_user_obj)
                self._check_register(status, msg)
        else:
            wx.MessageBox(str(msg), '错误提示', wx.OK | wx.ICON_ERROR)

    def _check_login(self, user_obj):
        status, msg = api_login(user_obj=user_obj)
        if status == 1000:
            # wx.MessageBox(msg, '成功提示', wx.OK | wx.ICON_INFORMATION)
            self.EndModal(wx.ID_OK)
            self.Destroy()
        else:
            wx.MessageBox(str(msg), '错误提示', wx.OK | wx.ICON_ERROR)


if __name__ == '__main__':
    app = wx.App()
    with LoginDialog(None) as dlg:
        dlg.ShowModal()
    app.MainLoop()
